<template>
	<view class="page page-primary page-index">
		<view class="page-content">
			<view class="page-content-title">
				<view class="user-wrapper">
					<image :src="userInfo.avatar || '/static/images/company/person-head.png'" class="user-avatar"></image>
					<view>
						<fui-text class="user-name" :text="userInfo.nickname" size="32" fontWeight="bold" color="#fff"></fui-text>
						<fui-text :text="roleText" size="24" color="#ededed"></fui-text>
					</view>
					<view class="user-company">{{ deptName }}</view>
				</view>

				<fui-bubble-box class="bubble-box" :maskClosable="true" size="28" :isMask="true" :items="items"
					direction="bottom" position="absolute" lineColor="#4B4B4B" right="110" background="#333333"
					:padding="['22rpx', '20rpx', '22rpx', '28rpx']" color="#FFFFFF" width="300" :show="showMenu"
					@click="itemClick" @close="showMenu = false">
					<fui-icon name="menu" color="#FFFFFF" @click="showMenu = true"></fui-icon>
				</fui-bubble-box>
			</view>

			<!-- 供应链 -->
			<view class="" v-if="userType == 1">
				<!-- 供应商 -->
				<CardFirstkind @click="jumpSupplier" :data="supplierData"></CardFirstkind>

				<!-- 商品 -->
				<CardSecondKind @click="jumpGoodsManagement" :data="product1Data"></CardSecondKind>

				<!-- 采购方 -->
				<CardFirstkind @click="jumpPurchaser" :data="procuringAgentData"></CardFirstkind>

				<!-- 活动 -->
				<CardFirstkind @click="jumpActivity('supply')" :data="events1Data"></CardFirstkind>

				<!-- 订单统计 -->
				<CardSecondKind @click="jumpOrder" :data="statisticsData"></CardSecondKind>
			</view>

			<!-- 供应商 -->
			<view class="supplier-box" v-else>
				<!-- 订单统计 -->
				<CardSecondKind class="card" @click="jumpOrder" :data="statisticsData"></CardSecondKind>

				<!-- 商品统计 -->
				<CardSecondKind class="card" @click="jumpGoodsManagement" :data="product2Data"></CardSecondKind>

				<!-- 活动统计 -->
				<CardFirstkind class="card card-last" :data="events2Data" @clicked="jumpActivity('supplier', $event)"></CardFirstkind>
			</view>

			<view class="tendency">商品销售趋势图</view>
			<TendencyEcharts :yearXAxisData="yearXAxisData" :yearYAxisData="yearYAxisData" :monthXAxisData="monthXAxisData" :monthYAxisData="monthYAxisData"></TendencyEcharts>

			<view class="" v-if="userType == 1">
				<view class="tendency-box">
					<view class="tendency">供应商销售排名</view>
					<view class="change-btn">
						<view :class="isMonth1 ? 'select-date' : 'date'" @click="isMonth1 = true">本月</view>
						<view :class="{ 'select-date': !isMonth1, date: isMonth1, years: true }" @click="isMonth1 = false">
							本年
						</view>
					</view>
				</view>
				<RankingTable :tableData="isMonth1 ? table1Data : table2Data" :headerData="header1Data"></RankingTable>
			</view>
			<view class="tendency-box">
				<view class="tendency">商品分类销售排名</view>
				<view class="change-btn">
					<view :class="isMonth2 ? 'select-date' : 'date'" @click="isMonth2 = true">本月</view>
					<view :class="{ 'select-date': !isMonth2, date: isMonth2, years: true }" @click="isMonth2 = false">本年
					</view>
				</view>
			</view>
			<RankingTable class="ranking-table" :tableData="isMonth2 ? table3Data : table4Data" :headerData="header2Data"></RankingTable>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, inject } from 'vue'
  import { onLoad, onShow } from "@dcloudio/uni-app"
	import { useStore } from 'vuex'
  import { getAccessToken } from '@/utils/auth'
	import CardFirstkind from '@/components/card/firstKind'
	import CardSecondKind from '@/components/card/secondKind'
	import TendencyEcharts from '@/components/home/tendencyEcharts'
	import RankingTable from '@/components/home/rankingTable'
	import supplierApi from '@/api/supplier'
  import { formatValue, formatUnit } from '@/utils/tools'

	const store = useStore();
	const modal = inject('$modal');
	const tab = inject('$tab');
	const auth = inject('$auth');

	// 用户信息
	const { roles, userType } = store.getters
	const userInfo = computed(() => store.getters.userInfo)
	const deptName = computed(() => store.getters.currentDeptName)
	const roleText = computed(() => {
		if (roles.indexOf('scm_gyl_yyjl') > -1) {
			return '供应链负责人'
		} else if (roles.indexOf('scm_gysfzr') > -1) {
			return '供应商负责人'
		} else if (userInfo.value.roles && userInfo.value.roles[0]) {
			return userInfo.value.roles[0].name
		} else {
			return ''
		}
	})

  // 检查页面跳转
  const jumpValidator = () => {
    if (!getAccessToken()) {
      modal.msgError('请先登录！')
      tab.reLaunch('/pages/login')
      return false
    }
    if (userInfo.value.rzzt != 1) {
      tab.reLaunch('/pages/unauthorized')
			return false
    }
		return true
  }

	const supplierData = ref({
		title: '供应商管理',
		number1: 0,
		number2: 0,
		status1: '已有',
		status2: '待审核',
		color: 'var(--fui-color-primary)',
		unit: '个'
	});

	const procuringAgentData = ref({
		title: '采购方管理',
		number1: 0,
		number2: 0,
		status1: '已有',
		status2: '待审核',
		color: '#3CDBCD',
		unit: '个'
	});

	const events1Data = ref({
		title: '促销活动',
		number1: 0,
		number2: 0,
		status1: '全部活动',
		status2: '进行中',
		color: '#F95A5A',
		unit: '个'
	});

	const events2Data = ref({
		title: '促销活动',
		number1: 0,
		number2: 0,
		status1: '我创建的',
		status2: '可报名的',
		color: '#F95A5A',
		unit: '个'
	});

	const product1Data = ref({
		title: '商品管理',
		number1: 0,
		number2: 0,
		number3: 0,
		number4: 0,
		label1: '商品价值',
		label2: '商品数量',
		label3: '自营数量',
		label4: '直供数量',
		unit1: '个',
		unit2: '个',
		unit3: '个',
		color: '#5A4BFA',
    unit: '元'
	});

  const product2Data = ref({
		title: '商品管理',
		number1: 0,
		number2: 0,
		label1: '商品价值',
		label2: '商品数量',
		unit1: '个',
		unit2: '个',
		color: '#5A4BFA',
    unit: '元'
	});

	const statisticsData = ref({
		title: '订单管理',
		number1: 0,
		number2: 0,
		number3: 0,
		number4: 0,
		number5: 0,
		label1: '订单销售额',
		label2: '已完成',
		label3: '订单数',
		label4: '待发货',
		label5: '待收货',
		unit1: '单',
		unit2: '单',
		unit3: '单',
		unit4: '单',
		color: '#FCAD4C',
    unit: '元'
	});

	// 供应商销售排名 表头
	const header1Data = ref([{
			prop: 'ranking',
			label: '排名'
		},
		{
			prop: 'name',
			label: '供应商名称'
		},
		{
			prop: 'salesVolume',
			label: '销售额(万元)'
		}
	]);

	// 商品分类销售排名 表头
	const header2Data = ref([{
			prop: 'ranking',
			label: '排名'
		},
		{
			prop: 'name',
			label: '商品分类名称'
		},
		{
			prop: 'salesVolume',
			label: '销售额(万元)'
		}
	]);

  // 供应商销售排名 数据
	const table1Data = ref([]);
  const table2Data = ref([])

	// 商品分类销售排名 数据
	const table3Data = ref([]);
	const table4Data = ref([]);

	const isMonth1 = ref(true);
	const isMonth2 = ref(true);

  // 商品销售趋势数据
  const yearXAxisData = ref([])
  const yearYAxisData = ref([])
  const monthXAxisData = ref([])
  const monthYAxisData = ref([])

	const { currentTenantId, currentDeptId } = store.getters
	const getHomeData = () => {
		try {
			supplierApi.getHomeData({
				zhid: currentTenantId,
				gsid: currentDeptId,
				yhlx: userType
			}).then(res => {
				if (res.code === 0 && res.data) {
          // 商品销售额趋势
          yearXAxisData.value = res.data.spxsqs_bn.map(item => userType === '1' ? item.jbid : item.sjpx)
          yearYAxisData.value = res.data.spxsqs_bn.map(item => item.val00 / 1)
          monthXAxisData.value = res.data.spxsqs_by.map(item => userType === '1' ? item.jbid : item.sjpx)
          monthYAxisData.value = res.data.spxsqs_by.map(item => item.val00 / 1)

          if (userType === '1') {
            // 供应商/采购方/活动统计数据
            supplierData.value.number1 = res.data.jbxx && res.data.jbxx[0] ? res.data.jbxx[0].val00 : 0
            supplierData.value.number2 = res.data.jbxx && res.data.jbxx[0] ? res.data.jbxx[0].val01 : 0
            procuringAgentData.value.number1 = res.data.jbxx && res.data.jbxx[0] ? res.data.jbxx[0].val02 : 0
            procuringAgentData.value.number2 = res.data.jbxx && res.data.jbxx[0] ? res.data.jbxx[0].val03 : 0

            // 商品统计数据
            product1Data.value.number1 = res.data.sptjxx[0] ? res.data.sptjxx[0].val00 : 0
            product1Data.value.number2 = res.data.sptjxx[0] ? res.data.sptjxx[0].val01 : 0
            product1Data.value.number3 = res.data.sptjxx[0] ? res.data.sptjxx[0].val03 : 0
            product1Data.value.number4 = res.data.sptjxx[0] ? res.data.sptjxx[0].val04 : 0

            // 订单统计数据
            statisticsData.value.number1 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val00 : 0
            statisticsData.value.number2 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val03 : 0
            statisticsData.value.number3 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val02 : 0
            statisticsData.value.number4 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val04 : 0
            statisticsData.value.number5 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val05 : 0

						// 活动统计数据
						events1Data.value.number1 = res.data.hdtjxx && res.data.hdtjxx[0] ? res.data.hdtjxx[0].val00 : 0
						events1Data.value.number2 = res.data.hdtjxx && res.data.hdtjxx[0] ? res.data.hdtjxx[0].val02 : 0
            
            // 供应商销售排名
            table1Data.value = res.data.gysxspm_by.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.jbmc,
                salesVolume: item.val00
              }
            })
            table2Data.value = res.data.gysxspm_bn.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.jbmc,
                salesVolume: item.val00
              }
            })

            // 商品分类销售排名
            table3Data.value = res.data.spflxspm_by.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.jbmc,
                salesVolume: item.val00
              }
            })
            table4Data.value = res.data.spflxspm_bn.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.jbmc,
                salesVolume: item.val00
              }
            })
          } else {
            // 商品统计数据
            product2Data.value.number1 = res.data.sptjxx[0] ? res.data.sptjxx[0].val00 : 0
            product2Data.value.number2 = res.data.sptjxx[0] ? res.data.sptjxx[0].val01 : 0

            // 订单统计数据
            statisticsData.value.number1 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val00 : 0
            statisticsData.value.number2 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val03 : 0
            statisticsData.value.number3 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val02 : 0
            statisticsData.value.number4 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val04 : 0
            statisticsData.value.number5 = res.data.ddtjxx[0] ? res.data.ddtjxx[0].val05 : 0

						// 活动统计数据
						events2Data.value.number1 = res.data.hdtjxx && res.data.hdtjxx[0] ? res.data.hdtjxx[0].val00 : 0
						events2Data.value.number2 = res.data.hdtjxx && res.data.hdtjxx[0] ? res.data.hdtjxx[0].val01 : 0

            // 商品分类销售排名
            table3Data.value = res.data.spflxspm_by.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.val02,
                salesVolume: item.val00
              }
            })
            table4Data.value = res.data.spflxspm_bn.map((item, index) => {
              return {
                ...item,
                ranking: index + 1,
                name: item.val02,
                salesVolume: item.val00
              }
            })
          }
          // 判断单位是万元、亿元、万个等
          //商品单位
          product1Data.value.unit = formatUnit(product1Data.value.number1, '元')
          product1Data.value.unit1 = formatUnit(product1Data.value.number2, '个')
          product1Data.value.unit2 = formatUnit(product1Data.value.number3, '个')
          product1Data.value.unit3 = formatUnit(product1Data.value.number4, '个')
          
          product1Data.value.number1 = formatValue(product1Data.value.number1)
          product1Data.value.number2 = formatValue(product1Data.value.number2)
          product1Data.value.number3 = formatValue(product1Data.value.number3)
          product1Data.value.number4 = formatValue(product1Data.value.number4)
          
          product2Data.value.unit = formatUnit(product2Data.value.number1, '元')
          product2Data.value.unit1 = formatUnit(product2Data.value.number2, '个')
          
          product2Data.value.number1 = formatValue(product2Data.value.number1)
          product2Data.value.number2 = formatValue(product2Data.value.number2)
          // 订单单位
          statisticsData.value.unit = formatUnit(statisticsData.value.number1, '元')
          statisticsData.value.unit1 = formatUnit(statisticsData.value.number2, '单')
          statisticsData.value.unit2 = formatUnit(statisticsData.value.number3, '单')
          statisticsData.value.unit3 = formatUnit(statisticsData.value.number4, '单')
          statisticsData.value.unit4 = formatUnit(statisticsData.value.number5, '单')
          
          statisticsData.value.number1 = formatValue(statisticsData.value.number1)
          statisticsData.value.number2 = formatValue(statisticsData.value.number2)
          statisticsData.value.number3 = formatValue(statisticsData.value.number3)
          statisticsData.value.number4 = formatValue(statisticsData.value.number4)
          statisticsData.value.number5 = formatValue(statisticsData.value.number5)
				}
			})
		} catch(err) {
			modal.msgError('获取统计数据失败！')
		}
	}

	const isShowData = ref(false)
  onLoad(() => {
		isShowData.value = jumpValidator()
  })
	onShow(() => {
		if (isShowData.value) {
      getHomeData()
		}
	})

	// 隐藏菜单
  	const items = computed(() => {
		let arr = [{
				text: '我的信息',
				src: '/static/images/homePage/menu1.png',
				width: 37.33,
				height: 28.55,
				path: '/pages/user/profile'
			}]
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gysfzr'])) {
			arr = [
				...arr,
				{
					text: '公司管理',
					src: '/static/images/homePage/menu2.png',
					width: 37.33,
					height: 32.15,
					path: '/pages/company/index'
				}
			]
		}
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_scgl'])) {
			arr = [
				...arr,
				{
					text: '商城管理',
					src: '/static/images/homePage/menu3.png',
					width: 31.8,
					height: 37.38,
					path: '/pages/mall/index'
				},
				{
					text: '轮播图管理',
					src: '/static/images/homePage/menu4.png',
					width: 39.39,
					height: 30.99,
					path: '/pages/carousel/Index'
				}
			]
		}
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gysfzr'])) {
			arr = [
				...arr,
				{
					text: '发货地管理',
					src: '/static/images/homePage/menu5.png',
					width: 36.93,
					height: 33.74,
					path: '/pages/dispatch/list'
				}
			]
		}
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_hdgl', 'scm_gysfzr', 'scm_gysspzy'])) {
			arr = [
				...arr,
				{
					text: '优惠券管理',
					src: '/static/images/homePage/menu9.png',
					width: 36.93,
					height: 33.74,
					path: '/pages/coupon/list'
				}
			]
		}
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_spgl', 'scm_gysfzr', 'scm_gysspzy'])) {
			arr = [
				...arr,
				{
					text: '商品运费设置',
					src: '/static/images/homePage/menu8.png',
					width: 36.93,
					height: 33.74,
					path: '/pages/carriage/list'
				}
			]
		}
		if (auth.hasRoleOr(['scm_gysfzr'])) {
			arr = [
				...arr,
				{
					text: '售后处理',
					src: '/static/images/homePage/menu11.png',
					width: 36.93,
					height: 33.74,
					path: '/pages/aftersale/list'
				}
			]
		}
		arr = [
			...arr,
			{
				text: '投诉与反馈',
				src: '/static/images/homePage/menu10.png',
				width: 36.93,
				height: 33.74,
				path: '/pages/contact'
			}
		]
		return arr
	})

	// 菜单点击事件
	const showMenu = ref(false);
	const itemClick = (e) => {
		showMenu.value = false
    const item = items.value[e.index]
    if (item.path) {
      tab.navigateTo(item.path)
    }
    if (item.func) {
      item.func()
    }
	};

	// 获取商品分类模板，存在全局categoryTempList中
	store.dispatch('getCategoryTempList');

	// 获取商品分类，存在全局productCategoryList中
	store.dispatch('getCategoryList');

	// 跳转订单统计
	const jumpOrder = () => {
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_ddgl', 'scm_gyl_fhgl', 'scm_gysfzr', 'scm_gysddzy', 'scm_gysfhzy'])) {
		uni.navigateTo({
			url: '/pages/order/index'
		});
		}
	};

	// 跳转商品管理
	const jumpGoodsManagement = () => {
    if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_spgl', 'scm_gysfzr', 'scm_gysspzy'])) {
      uni.navigateTo({
        url: '/pages/goods/index'
      });
    }
	};

	// 跳转活动统计
	const jumpActivity = (type, index) => {
		if (type === 'supply' && auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_hdgl'])) {
			uni.navigateTo({
				url: `/pages/activity/supply/list`
			});
		}
		if (type === 'supplier' && auth.hasRoleOr(['scm_gysfzr', 'scm_gysspzy'])) {
			if (index == 0) {
				uni.navigateTo({
					url: `/pages/activity/supplier/list`
				});
			} else {
				uni.navigateTo({
					url: `/pages/activity/joinin/list`
				});
			}
		}
	};

  	// 跳转供应商
	const jumpSupplier = () => {
    if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_gysgl'])) {
      uni.navigateTo({
        url: `/pages/supplier/index`
      });
    }
	};

  	// 跳转采购方
	const jumpPurchaser = () => {
		if (auth.hasRoleOr(['scm_gyl_yyjl', 'scm_gyl_cgfgl'])) {
		uni.navigateTo({
			url: `/pages/purchaser/index`
		});
		}
	};
</script>

<style lang="scss" scoped>
	.page {
		.numStyle {
			color: var(--fui-color-primary);
			font-weight: bold;
		}

		.gray-text {
			font-size: 24rpx;
			font-weight: 400;
			color: #666666;
		}

		.page-content {
			padding-bottom: 50rpx;

			.page-content-title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #ffffff;
				font-size: 36rpx;
				font-weight: bold;
				margin-bottom: 42rpx;
			}
		}

		.user-wrapper {
			position: relative;
			padding-left: 100rpx;
			.user-avatar {
				position: absolute;
				top: 50%;
				left: 0;
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				border: 2rpx solid rgba(255, 255, 255, .2);
				margin-top: -40rpx;
			}
			.user-name {
				margin-right: 20rpx;
			}
			.user-company {
				margin-top: 10rpx;
				font-size: 24rpx;
				font-weight: normal;
				color: #ccc;
			}
		}

		.tendency-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.tendency {
			font-size: 32rpx;
			font-weight: bold;
			color: #000000;
			margin-top: 30rpx;
		}

		.change-btn {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			font-size: 24rpx;
			font-weight: 400;
			padding: 20rpx;
			padding-bottom: 0;

			.select-date {
				background: var(--fui-color-primary);
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				padding: 4rpx 22rpx 2rpx;
				color: #ffffff;
			}

			.date {
				background: #ffffff;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2rpx solid var(--fui-color-primary);
				color: var(--fui-color-primary);
				padding: 4rpx 22rpx 2rpx;
			}

			.years {
				margin-left: 20rpx;
			}
		}

		.supplier-box {
			display: flex;
			width: 100vw;
			overflow-x: auto;
			overflow-y: hidden;
			margin-left: -36rpx;

			.card {
				margin-left: 36rpx;
				flex: 0 0 calc(100vw - 110rpx) !important;
			}

			.card-last {
				margin-right: 36rpx;
			}
		}

		/* 设置滚动条宽度 */
		.supplier-box::-webkit-scrollbar {
			height: 0;
		}
	}
</style>